from retrievingant import retriever
from wingedant import airborne
from ant import Ant
from paintingant import painter
from mutagen.mp3 import MP3
from mutagen.id3 import TALB,TPE1,ID3
import threading,Queue,sys,string,os,shutil,time
class supplier(threading.Thread, Ant):
	pile = Queue.Queue()
	folder=""
	local={}
	locallock=threading.Lock()
	filelock=threading.Lock()		
	def run(self):
		while True:
			twig = supplier.pile.get()
			#
			Ant.leave("supplier")
			temp=self.fetchtwig(twig)
			if(temp!=""):
				retriever.pile.put(temp)
			supplier.pile.task_done()
			Ant.comehome("supplier")

	def fetchtwig(self,path):
		pt={}
		pt['command_string']=Ant.__commandstring__
		path=str.rstrip(path)
		if "Z:" in path:								##C#LINUX FIX (Not needed)
			path=string.replace(path,"\\","/")
			path=string.replace(path,"Z:","")
			path.encode('latin1')
		deletelist=['incomplete','commercial','advertisement']
		for item in deletelist:
                        if item in path.lower():						##C# PURGE incomplete files								#
                                print("\n\n\n DELETED FILE "+path+"\n\n\n")		#
                                os.remove(path)										#
                                return ""											#
                                ##T# Actual beginning
		try: pt['file_to_tag'] = MP3(path, ID3=ID3)#
		except IOError:
                        print("Cannot access file "+path+" probably because of name contains non-ascii chars")
                        return ""
		try:pt['artist_tag']=self.kickfeat(pt['file_to_tag']['TPE1'][0].lower())
		except KeyError:return ""
		try:pt['track_tag']=self.kickparentheses(pt['file_to_tag']['TIT2'][0].lower())
		except KeyError:
                        pt['track_tag']=""
                        if("a" in pt['command_string']):
                                return ""
		try:
                        pt['album_tag']=pt['file_to_tag']['TALB'][0].lower()
                        pt['atag_present']=1
		except KeyError:pass
		if("g" in pt['command_string']):
                        if(pt['artist_tag'] in supplier.local):
                                if(supplier.local[pt['artist_tag']]=="work"):
                                        supplier.pile.put(path)
                                elif (supplier.local[pt['artist_tag']]=="closed"):
                                        return pt
                                else:
                                        #print (supplier.local[pt['artist_tag']]+"!!")
                                        pt['genre_tag']=supplier.local[pt['artist_tag']]
                                        print "derp success"
                                       # print pt['genre_tag']
                                        painter.pile.put(pt)
                                return ""
                                        
                        else:
                                supplier.locallock.acquire()
                                supplier.local[pt['artist_tag']]="work"
                                supplier.locallock.release()
                
		return pt									# fail and exit
					###do some basic formatting
						###R# All went well. Return info with 3 Arguments
	def kickfeat(self,passed):
                passed=passed.lower()
                if("ft." in passed):
                   passed=passed[:passed.find("ft.")]     
		if(" ft" in passed):						##C# Modify Tags containting "Featuring" or such
		   passed=passed[:passed.find(" ft")]			#
		if(" feat" in passed):									#
		   passed=passed[:passed.find(" feat")]
		if("," in passed):									#
		   passed=passed[:passed.find(",")]
		if("feat" in passed)and ("defeat" not in passed):	#
		   passed=passed[:passed.find("feat")]
		passed=passed.rstrip()
		return passed
	def kickparentheses(self,passed):
                passed=passed.lower()
                if("(" in passed):
                        passed=passed[:passed.find("(")]
                return passed
        @staticmethod
	def fail(what):
                #print "trying to acquire lock"
                supplier.locallock.acquire()
                #print "Lock acquired"
                supplier.local[what]="closed"
                supplier.locallock.release()
                #print "lock released"
        @staticmethod
        def succeed(what,gtag):
                #print "trying to acquire lock"
                supplier.locallock.acquire()
                #print "Lock acquired"
                supplier.local[what]=gtag
                supplier.locallock.release()
                #print "lock released"
